package com.longxi.tianjintianbao.ui.activity.assetscheck;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponseWebPd;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataInventoryController;
import com.longxi.tianjintianbao.greedao.entity.Inventory;
import com.longxi.tianjintianbao.greedao.entity.InventoryChild;
import com.longxi.tianjintianbao.ui.activity.scan.ScanActivity2;
import com.longxi.tianjintianbao.ui.adapter.multitype.assetscheck.TestViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.utils.AESUtil;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TestActivity extends BaseActivity {

    @BindView(R.id.tabLayout)
    SegmentTabLayout tabLayout;
    @BindView(R.id.tabLayout2)
    SegmentTabLayout tabLayout2;
    @BindView(R.id.tvOrderNo)
    TextView tvOrderNo;
    @BindView(R.id.etReceiptNumber)
    EditText etReceiptNumber;
    @BindView(R.id.btnDownload)
    Button btnSearch;
    @BindView(R.id.btnUpload)
    Button btnUpload;
    int chenggong = 1;
    int shibai = 2;

    private MultiTypeAdapter adapter;
    private Items items = new Items();
    private String[] tital = {"全部", "未盘", "已盘", "盘盈"};
    private String[] tital2 = {"0", "0", "0", "0"};
    private int mPosition = 0;
    private List<InventoryChild> all = new ArrayList<>();
    private List<InventoryChild> notSet = new ArrayList<>();
    private List<InventoryChild> haveSet = new ArrayList<>();
    private List<InventoryChild> FullSet = new ArrayList<>();
    private Map<String, List<InventoryChild>>  stringListMap = new HashMap<>();
    private int[] pages = {0, 0, 0, 0};
    private boolean[] isRefresh = {true, true, true, true};//判断是否要刷新
    private int limit = 10;
    Inventory inventory;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_test;
    }

    @Override
    public void initView() {
        super.initView();
        LogUtils.i("zp","啦啦啦");
        setTvLeft("返回");
        setTitle("资产盘点");
        setIvRight(R.mipmap.ic_scan);
        initAdapter();
        inventory = DataInventoryController.getPatrolByBillid(getIntent().getStringExtra(AppConst.BILLID));
        tvOrderNo.setText("单据编号: " + inventory.number);
        tabLayout.setTabData(tital);
        stringListMap.put("0", all);
        stringListMap.put("1", notSet);
        stringListMap.put("2", haveSet);
        stringListMap.put("3", FullSet);
        initTital();
    }

    /**
     * 初始化标题数据 后面加数据
     */
    private void initTital() {
        long c0 = DataInventoryController.SearchInventoryChildCount(inventory, 0);
        long c1 = DataInventoryController.SearchInventoryChildCount(inventory, 1);
        long c2 = DataInventoryController.SearchInventoryChildCount(inventory, 2);
        long c3 = DataInventoryController.SearchInventoryChildCount(inventory, 3);

        tital2[0] = "" + c0;
        tital2[1] = "" + c1;
        tital2[2] = "" + c2;
        tital2[3] = "" + c3;

        tabLayout2.setTabData(tital2);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(InventoryChild.class, new TestViewBinder(new TestViewBinder.OnClickListener() {
                @Override
                public void onClick(int position) {
                    InventoryChild inventoryChild = (InventoryChild) items.get(position);
                    Intent intent = new Intent(TestActivity.this, TestActivity2.class);
                    intent.putExtra(AppConst.BILLID, inventoryChild.getId());
                    startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_TEST2);
                }
            }));
            mRvContent.setAdapter(adapter);
            adapter.setItems(items);
        }
    }

    @Override
    public void initData() {
        super.initData();
        refresh();
    }

    @Override
    public void initListener() {
        super.initListener();

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mPosition = position;
                tabLayout2.setCurrentTab(mPosition);
                showUploadButton();
                if(isRefresh[mPosition]){
                    pages[mPosition]=0;
                    refresh();
                    return;
                }

                if(stringListMap.get(String.valueOf(mPosition)).size() > 0){
                    items.clear();
                    items.addAll(stringListMap.get(String.valueOf(mPosition)));
                    adapter.notifyDataSetChanged();
                    if(items.size() == 0){
                        showNoData();
                    }else{
                        hideLoading();
                    }
                    return;
                }
                pages[mPosition]=0;
                refresh();
            }

            @Override
            public void onTabReselect(int position) {
                showUploadButton();
                //刷新
                pages[mPosition]=0;
                refresh();
            }
        });

        tabLayout2.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mPosition = position;
                tabLayout.setCurrentTab(mPosition);
                showUploadButton();
                if(isRefresh[mPosition]){
                    pages[mPosition]=0;
                    refresh();
                    return;
                }

                if(stringListMap.get(String.valueOf(mPosition)).size() > 0){
                    items.clear();
                    items.addAll(stringListMap.get(String.valueOf(mPosition)));
                    adapter.notifyDataSetChanged();
                    if(items.size() == 0){
                        showNoData();
                    }else{
                        hideLoading();
                    }
                    return;
                }
                pages[mPosition]=0;
                refresh();
            }

            @Override
            public void onTabReselect(int position) {
                showUploadButton();
                //刷新
                pages[mPosition]=0;
                refresh();
            }
        });

        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                pages[mPosition]++;
                refresh();
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                showUploadButton();
                pages[mPosition]=0;
                refresh();
            }
        });

        mIvRight.setOnClickListener(view -> scan());
        btnUpload.setOnClickListener(v -> getUploadData());
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchLocalData(etReceiptNumber.getText().toString().trim());
            }
        });
    }

    public void scan() {
        AndPermission.with(this)
        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
        .onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Intent intent = new Intent(TestActivity.this, ScanActivity2.class);
                startActivityForResult(intent, AppConst.IntentRequstCode.REQUEST_CODE_SCAN);
            }
        })
        .onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(intent);

                MyUtils.showToast("没有权限无法扫描");
            }
        }).start();
    }

    private void refresh(){
        List<InventoryChild> list = new ArrayList<>();
        if(pages[mPosition] == 0){
            stringListMap.get(String.valueOf(mPosition)).clear();
            items.clear();
            isRefresh[mPosition] = false;
        }
        list = DataInventoryController.SearchInventoryChild(inventory, pages[mPosition], limit, mPosition);
        stringListMap.get(String.valueOf(mPosition)).addAll(list);
        items.addAll(list);
        if(mRefreshLayout.isRefreshing())
            mRefreshLayout.finishRefresh();
        if(mRefreshLayout.isLoading())
            mRefreshLayout.finishLoadMore();

        adapter.notifyDataSetChanged();
        if(items.size() == 0){
            showNoData();
        }else{
            hideLoading();
        }
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK){
            return;
        }

        switch (requestCode) {
            case AppConst.IntentRequstCode.REQUEST_CODE_SCAN:
                if (data != null) {
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_SUCCESS) {
                            String result = bundle.getString(AppConst.RESULT_STRING);
                            MyUtils.showToast(result);
                            search(result);
                        } else if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_FAILED) {
                            MyUtils.showToast("解析二维码失败");
                        }
                    }
                }
                break;
            case AppConst.IntentRequstCode.ACTIVITY_TEST2:
                isRefresh[0] = true;
                isRefresh[1] = true;
                isRefresh[2] = true;
                isRefresh[3] = true;
                mRefreshLayout.autoRefresh();

                initTital();
                break;
            case AppConst.IntentRequstCode.ACTIVITY_TEST_SEARCH:
                isRefresh[0] = true;
                isRefresh[1] = true;
                isRefresh[2] = true;
                isRefresh[3] = true;
                mRefreshLayout.autoRefresh();

                initTital();
                break;
        }
    }

    private void search(String searchCode){
        if(TextUtils.isEmpty(searchCode)){
            MyUtils.showToast("条形码不存在");
            return;
        }

        InventoryChild inventoryChild = DataInventoryController.insertInventoryChildDao(inventory.getId(), searchCode);
        if(inventoryChild != null){
            Intent intent = new Intent(TestActivity.this, TestActivity2.class);
            intent.putExtra(AppConst.BILLID, inventoryChild.getId());
            startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_TEST2);
            return;
        }

        inventoryChild = new InventoryChild();
        inventoryChild.iid = inventory.getId();
        inventoryChild.number = searchCode;
        inventoryChild.cagegory = "";
        inventoryChild.name = "";
        inventoryChild.department = "";
        inventoryChild.location = "";
        inventoryChild.gps = "";
        inventoryChild.booknum = -1;
        inventoryChild.inventorynum = -1;
        inventoryChild.specifications = "";
        inventoryChild.images = "";
        inventoryChild.unit = "";
        inventoryChild.isdraft = "0";
        inventoryChild.state = "1";
        DataInventoryController.insertInventoryChildDao(inventoryChild);

        Intent intent = new Intent(TestActivity.this, TestActivity2.class);
        intent.putExtra(AppConst.BILLID, inventoryChild.getId());
        startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_TEST2);

    }

    private void searchLocalData(String searchCode) {
        if (TextUtils.isEmpty(searchCode)) {
            MyUtils.showToast("条形码不存在");
            return;
        }

        Intent intent = new Intent(TestActivity.this, TestSearchActivity.class);
        intent.putExtra(AppConst.BILLID, getIntent().getStringExtra(AppConst.BILLID));
        intent.putExtra(AppConst.KEY_EXTRAS, searchCode);
        startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_TEST_SEARCH);
    }

    private int uploadNum = 0;
    private int position = 0;//我就是要这样写

    /**
     * 显示上传按钮用
     */
    private void showUploadButton(){
        uploadNum = 0;
        switch (mPosition) {
            case 0:
                btnUpload.setVisibility(View.GONE);
                break;
            case 1:
                btnUpload.setVisibility(View.GONE);
                break;
            case 2:
                btnUpload.setVisibility(View.VISIBLE);
                uploadNum = (int) DataInventoryController.isUploadData(inventory, mPosition);
                btnUpload.setText("盘点上传("+ uploadNum +")");
                break;
            case 3:
                btnUpload.setVisibility(View.VISIBLE);
                uploadNum = (int) DataInventoryController.isUploadData(inventory, mPosition);
                btnUpload.setText("盘盈上传("+ uploadNum +")");
                break;
        }
//        if(uploadNum > 0){
//            btnUpload.setVisibility(View.VISIBLE);
//        }else{
//            btnUpload.setVisibility(View.GONE);
//        }
    }

    private List<InventoryChild> inventoryChildList = new ArrayList<>();
    private int isUploadNum = 1;//当前已上传数量
    private int haveUploadNum = 0;

    /**
     * 批量上传
     */
    private void getUploadData() {
        isUploadNum = 1;
        uploadNum = (int) DataInventoryController.isUploadData(inventory, mPosition);
        if(uploadNum == 0){
            inventoryChildList.clear();
//            btnUpload.setVisibility(View.GONE);
            MyUtils.showToast("没有需要上传的数据");
            return;
        }

        inventoryChildList = DataInventoryController.getUploadList(inventory, mPosition);
        haveUploadNum = inventoryChildList.size();
        position = 0;

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    imagePathList = Arrays.asList(inventoryChildList.get(position).images.split(","));//取出images数据
                    if(!"".equals(inventoryChildList.get(position).images) && imagePathList.size() > 0){//如果有图片数据 就调用上传图片的方法
                        uploadImage();
                    }else{//没有图片就将这个上传
                        uploadInventory();
                    }
                } else {
                    Toast.makeText(TestActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传资产盘点信息
     */
    private void uploadInventory(){
        positionImage = 1;
        showWaitingDialog2("上传第" + isUploadNum + "条单据共" + haveUploadNum + "条单据");

        String usernameApassword = "";
        try {
            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
        } catch (Exception e) {
            e.printStackTrace();
        }


        InventoryChild inventoryChild = inventoryChildList.get(position);
        String[] imgs = inventoryChild.getImages().split(",");
        String img1AND2 = "";
        for (String imgPath : imgs) {
            String[] imgpppp = imgPath.split("/");
            img1AND2 += "\n" + (AppConst.PDIMAGEQZ + imgpppp[imgpppp.length - 1]).replace(".JPEG", "1.JPEG");
        }
        String billdata = inventoryChild.getNumber() + "," + inventoryChild.getInventorynum() + "," + inventoryChild.getGps() +
                "\n" + inventoryChild.getNumber() + img1AND2;
        JSONObject object = new JSONObject();
        try {
            object.put("type", "setData");
            object.put("validate", usernameApassword);
            object.put("billtype", "inventory");
            object.put("billcode", inventory.getNumber());
            object.put("billdata", billdata);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.i("zp","上传的完整数据是的："+object);
        ApiRetrofit.getInstance().validate(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponseWebPd>(this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                LogUtils.i("zp","资产上传失败啦onError方法"+(shibai++)+"次");
                hideWaitingDialog();
                MyUtils.showToast(throwable.message);
                refreshList();
            }

            @Override
            public void onNext(BaseResponseWebPd result) {
                hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    LogUtils.i("zp","资产上传失败啦code不是0："+(shibai++)+"次");
                    return;
                }

                position++;
                isUploadNum++;
                if(result.getData().contains("ERROR")){
                    inventoryChild.isdraft = "1";
                    MyUtils.showToast("上传失败");
                    LogUtils.i("zp","资产上传失败啦ERROR"+(shibai++)+"次");
                }else{
                    inventoryChild.isdraft = "2";
                    LogUtils.i("zp","资产上传成功"+(chenggong++)+"次");
                }
                inventoryChild.iid = inventory.getId();
                DataInventoryController.correctSportInfo(inventoryChild);
                if(position < inventoryChildList.size()){
                    imagePathList = Arrays.asList(inventoryChildList.get(position).images.split(","));//取出images数据
                    if(!"".equals(inventoryChildList.get(position).images) && imagePathList.size() > 0){//如果有图片数据 就调用上传图片的方法
                        uploadImage();
                    }else{//没有图片就将这个上传
                        uploadInventory();
                    }//为什么上传后还要走
                }else{
                    refreshList();
                }

            }
        });
    }

    private void refreshList(){
        isRefresh[0] = true;
        isRefresh[1] = true;
        isRefresh[2] = true;
        isRefresh[3] = true;
        mRefreshLayout.autoRefresh();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.inventoryChildList = null;
    }

    private List<String> imagePathList = new ArrayList<>();//当前需要上传的图片
    private int positionImage = 1;//当前上传图片的位置
    /**
     * 搞不懂怎么想的
     * 图片上传 先调用此方法把图片上传上去 然后在上传item列表的信息
     */
    private void uploadImage(){
        showWaitingDialog2("上传第" + isUploadNum + "条单据的第" + positionImage + "张图片");
        String usernameApassword = "";
        try {
            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String imagePath = imagePathList.get(positionImage - 1);
//        String base64 = MyUtils.imageToBase64(imagePath);

        Bitmap bitmap = MyUtils.imageZoom(imagePath, 100);
        if(bitmap == null){
            uploadInventory();
            return;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] bitmapBytes = baos.toByteArray();
        String base64 = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);

        JSONObject object = new JSONObject();
        String[] imgpppp = imagePath.split("/");

        try {
            object.put("type", "setData");
            object.put("validate", usernameApassword);
            object.put("billtype", "image");
            object.put("billcode", (AppConst.PDIMAGEQZ + imgpppp[imgpppp.length - 1]).replace(".JPEG", "1.JPEG"));
            object.put("billdata", base64);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().validate(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponseWebPd>(this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                hideWaitingDialog();
                MyUtils.showToast(throwable.message);
                refreshList();
            }

            @Override
            public void onNext(BaseResponseWebPd result) {
                hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                if(result.getData().contains("ERROR")){
//                    MyUtils.showToast("图片上传失败请重新试一试");
//                    return;
                }

                if(positionImage < imagePathList.size()){
                    positionImage++;
                    uploadImage();
                }else{
                    uploadInventory();
                }

            }
        });
    }

}
